package com.iot08.api.controller;

import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.api.utils.FileUtil;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 用于 微信小程序 获取语音时的转换问题
 * 需识别 iOS + 微信小程序 的请求头
 *
 * @Author: Weichao
 * @Date: 2024/03/29/15:21
 * @Description:
 */
@Slf4j
@Controller
@RequestMapping("getway")
public class WxSmallProgramAudioController {

    @Resource
    private BaseBucketTool baseBucketTool;

    @GetMapping("wxSmallProgram/getaudio/{fileName}")
    public void getwxacodeunlimit(@PathVariable("fileName") String fileName, HttpServletRequest req, HttpServletResponse resp){
        try {
            /*

            # 安卓手机, 微信小程序 请求头
            user-agent : Mozilla/5.0 (Linux; Android 14; 23113RKC6C Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/116.0.0.0 Mobile Safari/537.36 XWEB/1160083 MMWEBSDK/20231202 MMWEBID/8242 MicroMessenger/8.0.47.2560(0x28002F51) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android

            # iOS手机, 微信小程序 请求头
            user-agent : Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.37(0x1800252f) NetType/WIFI Language/zh_CN

            */


            //判断是否 iOS + 微信小程序
            //获取不区分大小写, 统一小写
            String userAgent = req.getHeader("user-agent");
            log.info("微信 获取语音时的转换 userAgent:{}", userAgent);
            boolean isChange = false;
            if(userAgent.contains("iPhone") && userAgent.contains("MicroMessenger")){
                //iOS + 微信 (目前无法分辨到小程序)
                isChange = true;
            }

            isChange = true;


            //切分
            String url = req.getRequestURI();
            String regex = "/";
            String[] strings = url.split(regex);
            // eg: 20240312APPk0ttnsgyj1bzs.mp3
            fileName = strings[strings.length - 1];

            //替换成OSS上的文件URL
            String targetPath = BaseBucketTool.MESSAGE_COMMON_PATH + fileName;
            String oldPath = BaseBucketTool.MESSAGE_COMMON_PATH + fileName.replace(".mp3",".amr");

            if(isChange &&  fileName.contains(".mp3")){
                //是 iOS + 微信 且是要读 MP3 的音频文件
                //查存不存在 targetPath
                try{
                    boolean isExist = baseBucketTool.checkPath(targetPath);
                    if(!isExist){
                        // 不存在
                        // 临时文件目录
                        String tmpDir = "/tmp/";
                        File tempDirFile = new File(tmpDir+BaseBucketTool.MESSAGE_COMMON_PATH);
                        if(!tempDirFile.exists() && tempDirFile.isDirectory()){
                            boolean res = tempDirFile.mkdirs();
                        }
                        //下载
                        ByteArrayOutputStream oldFileData = baseBucketTool.downloadFileStream(oldPath);

                        File tempFile = new File(tmpDir + oldPath);
                        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
                            // 将 ByteArrayOutputStream 中的内容写入文件
                            oldFileData.writeTo(fileOutputStream);
                        } catch (Exception e) {
                            log.error("ByteArrayOutputStream 写入是报错 e:"+e.getMessage(), e);
                        } finally {
                            try {
                                // 关闭 ByteArrayOutputStream
                                oldFileData.close();
                            } catch (Exception e) {
                                log.error("ByteArrayOutputStream 关闭错误 e:"+e.getMessage(), e);
                            }
                        }

                        File tempTargetFile = new File(tmpDir + targetPath);
                        //转码后上传到OSS, 然后跳转 去 OSS下载新的
                        boolean changeRes = FileUtil.amrToMp3(tempFile, tempTargetFile);
                        if(changeRes){
                            FileInputStream fileInputStream = new FileInputStream(tempTargetFile);
                            baseBucketTool.upload(targetPath, fileInputStream, 2);
                            log.info("amr 转 mp3 成功, 上传OSS:{}", targetPath);
                        }
                        //删除临时文件
                        if(tempFile.exists()){
                            tempFile.delete();
                        }
                        if(tempTargetFile.exists()){
                            tempTargetFile.delete();
                        }
                        log.info("删除临时文件成功, {} 和 {} ", tmpDir + targetPath, tmpDir + oldPath);

                    }
                    //直接返回 redirect 重定向转换后的
                    resp.sendRedirect(baseBucketTool.getDOMAIN() + targetPath);
                    return;
    //                return "redirect:" + baseBucketTool.getDOMAIN() + targetPath;
                }catch (Exception e){
                    //直接返回  重定向转换后的
                    resp.sendRedirect(baseBucketTool.getDOMAIN() + oldPath);
    //                return "redirect:" + baseBucketTool.getDOMAIN() + oldPath;
                    return;
                }
            }
            resp.sendRedirect(baseBucketTool.getDOMAIN() + oldPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



}
